package com.updesignsz.admin.controller;

import com.updesignsz.admin.service.RoleService;
import com.updesignsz.admin.util.ResponseUtil;
import com.updesignsz.admin.vo.form.RoleForm;
import com.updesignsz.commom.entity.Role;
import com.updesignsz.commom.entity.RoleFunction;
import com.updesignsz.commom.util.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 * Created User: lx
 * Date: 2020/4/29 14:44
 */
@RestController
public class RoleController {

    @Autowired
    private RoleService roleService;

    @GetMapping("/role")
    public void listAll(HttpServletResponse response) {
        ResultVo vo = new ResultVo();
        vo.setData(roleService.listAll());
        ResponseUtil.outJson(vo.toJsonMsg(), response);
    }


    @DeleteMapping("/role/{roleId}")
    public void deleteRole(@PathVariable Integer roleId, HttpServletResponse response) {
        ResultVo vo = new ResultVo();
        roleService.deleteRole(roleId);
        ResponseUtil.outJson(vo.toJsonMsg(), response);
    }


    @PostMapping("/role")
    public void addRole(@Validated(PostMapping.class) @RequestBody RoleForm form, HttpServletResponse response) {
        ResultVo vo = new ResultVo();
        Role role = convert(form);
        roleService.saveRole(role);
        vo.setData(roleService.getByRoleId(role.getId()));
        ResponseUtil.outJson(vo.toJsonMsg(), response);
    }



    /**
     * 将表单转成对象
     */
    private Role convert(RoleForm form) {
        Role role = new Role();
        role.setName(form.getName());
        role.setIdentifier(form.getIdentifier());
        role.setId(role.getId());
        List<Integer> functions = form.getFunctions();
        List<RoleFunction> functionList = new ArrayList<>();
        for (Integer functionId : functions) {
            RoleFunction function = new RoleFunction();
            function.setFunctionId(functionId);
            functionList.add(function);
        }
        role.setRoleFunctions(functionList);
        return role;
    }
}
